<!-- eslint-disable vue/valid-v-slot -->
<template>
  <v-container>
    <v-row>
      <v-col>
        <v-btn block ripple elevation="8" color="surface-variant" @click="createDialogActiveFlag = true">新建</v-btn>
      </v-col>
    </v-row>
    <v-row>
      <v-data-table :headers="headers" :items="projects">
        <template v-slot:item.buildCommand="{ value }">
          {{ Object.keys(value).length }}步骤
        </template>
        <template v-slot:item.environment="{ value }">
          {{ Object.keys(value).length }}环境变量
        </template>
        <template v-slot:item.action="{ item }">
          <v-btn small density="comfortable" prependIcon="mdi-cog" @click="configItem(item)">配置</v-btn>
          <v-btn small density="comfortable" prependIcon="mdi-pen" @click="editItem(item)">编辑</v-btn>
          <v-btn small density="comfortable" prependIcon="mdi-delete" @click="deleteItem(item.id!)">删除</v-btn>
        </template>
      </v-data-table>


    </v-row>
  </v-container>

<!--修改对话框-->
  <v-dialog v-model="editDialogActiveFlag" max-height="800">
    <v-card>
      <v-card-title>编辑</v-card-title>
      <v-card-text>
        <v-container>
          <v-row>
            <v-col cols="6">
              <v-text-field v-model="editingProject.name" label="名称"></v-text-field>
            </v-col>
            <v-col cols="6">
              <v-text-field v-model="editingProject.description" label="描述"></v-text-field>
            </v-col>
            <v-col cols="6">
              <v-text-field v-model="editingProject.gitUrl" label="Git仓库"></v-text-field>
            </v-col>
            <v-col cols="6">
              <v-text-field v-model="editingProject.branch" label="分支"></v-text-field>
            </v-col>
            <v-col cols="12">
              <v-btn block prepend-icon="mdi-check-circle" @click="handelEditSubmit">完成</v-btn>
            </v-col>
            <v-col cols="12">
              <v-btn block @click="handleEditCancel">取消</v-btn>
            </v-col>
          </v-row>
        </v-container>
      </v-card-text>
    </v-card>
  </v-dialog>

<!--新增对话框-->
  <v-dialog v-model="createDialogActiveFlag" max-width="500">
    <v-card>
      <v-card-title>新增</v-card-title>
      <v-card-text>
        <v-container>
          <v-row>
            <v-col cols="6">
              <v-text-field v-model="creatingProject.name" label="名称"></v-text-field>
            </v-col>
            <v-col cols="6">
              <v-text-field v-model="creatingProject.description" label="描述"></v-text-field>
            </v-col>
            <v-col cols="6">
              <v-text-field v-model="creatingProject.gitUrl" label="Git仓库"></v-text-field>
            </v-col>
            <v-col cols="6">
              <v-text-field v-model="creatingProject.branch" label="分支"></v-text-field>
            </v-col>
            <v-col cols="12">
              <v-btn block prepend-icon="mdi-check-circle" @click="handleCreateSubmit">完成</v-btn>
            </v-col>
            <v-col cols="12">
              <v-btn block @click="handleCreateCancel">取消</v-btn>
            </v-col>
          </v-row>
        </v-container>
      </v-card-text>
    </v-card>
  </v-dialog>

  <!--  Delete Dialog-->
  <v-dialog v-model="deleteDialogActiveFlag" max-width="500">
    <v-card title="确认删除">
      <v-card-text>确认删除项目吗</v-card-text>
      <v-card-actions>
        <v-spacer/>
        <v-btn color="primary" @click="deleteItemConfirm">确定</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>

  <!--  Config Dialog-->
  <v-dialog v-model="configDialogActiveFlag" max-width="800">
    <v-card-title>
      <v-tabs v-model="tab" bg-color="primary">
        <v-tab ripple value="cmd">构建命令</v-tab>
        <v-tab ripple value="env">环境变量</v-tab>
      </v-tabs>
    </v-card-title>
    <v-card-subtitle>
      <v-btn small block  @click="handleAddConfig">添加</v-btn>
    </v-card-subtitle>
    <v-card-text>
      <v-data-table :headers="configHeaders" :items="configDatas">
        <template v-slot:item.action="{ item }">
          <v-btn small density="comfortable" icon="mdi-delete" @click="configDeleteItem(item)"></v-btn>
        </template>
      </v-data-table>
    </v-card-text>
  </v-dialog>

<!--  Add config Dialog-->
  <v-dialog v-model="addConfigDialogActiveFlag" max-width="400">
    <v-card>
      <v-container>
        <v-row>
          <v-col cols="4">
            <v-text-field v-model="currentConfig.name" label="名称"/>
          </v-col>
          <v-col cols="8">
            <v-text-field v-model="currentConfig.value" :label="tab === 'cmd' ? '命令' : '值'"/>
          </v-col>
        </v-row>
        <v-row>
          <v-col cols="12">
            <v-btn block color="primary" icon="mdi-check" @click="submitAddConfig"></v-btn>
          </v-col>
        </v-row>
      </v-container>
    </v-card>
  </v-dialog>

</template>

<script setup lang="ts">

import {onMounted, ref, watch} from "vue";
import Project from "@/types/Project";
import Response from '@/types/Response';
import {doDelete, doGet, doPost, doPut} from "@/http";


const headers = [
  {title: 'ID', key: 'id'},
  {title: '名称', key: 'name'},
  {title: '描述', key: 'description'},
  {title: 'Git仓库', key: 'gitUrl'},
  {title: '分支', key: 'branch'},
  {title: '构建命令', key: 'buildCommand'},
  {title: '环境变量', key: 'environment'},
  {title: '操作', key: 'action'}
]
const projects = ref([] as Project[])

const createDialogActiveFlag = ref(false);
const editDialogActiveFlag = ref(false)
const deleteDialogActiveFlag = ref(false)
const configDialogActiveFlag = ref(false)
const addConfigDialogActiveFlag = ref(false)

const editingProject = ref({} as Project)
const creatingProject = ref({} as Project)
const deleting = ref(-1)

const tab = ref('')
const currentConfiguringProject = ref({} as Project)
const configHeaders = ref([] as any[])
const cmdHeaders = [
  {title: '名称', key: 'name'},
  {title: '命令', key: 'command'},
  {title: '操作', key: 'action'}
]

const envHeaders = [
  {title: '名称', key: 'name'},
  {title: '值', key: 'value'},
  {title: '操作', key: 'action'}
]

const configDatas = ref([] as any)

const editItem = (item: Project) => {
  editDialogActiveFlag.value = true
  editingProject.value = item
}

const currentConfig = ref({} as any)


const handleAddConfig = () => {
  addConfigDialogActiveFlag.value = true
}

const submitAddConfig = async () => {
  if (tab.value === 'cmd') {
    currentConfiguringProject.value.buildCommand.push({
      name: currentConfig.value.name,
      command: (currentConfig.value.value as string).split(" ")
    })
  } else if (tab.value === 'env') {
    currentConfiguringProject.value.environment.push({
      name: currentConfig.value.name,
      value: currentConfig.value.value as string
    })
  }

  addConfigDialogActiveFlag.value = false
  configDialogActiveFlag.value = false
  doPut('/projects', currentConfiguringProject.value)
  currentConfig.value = {}
  projects.value = (await doGet('/projects')).data

}

const handleCreateSubmit = async () => {
  createDialogActiveFlag.value = false
  doPost('/projects', creatingProject.value)
  projects.value = (await doGet('/projects')).data
}

const handleCreateCancel = () => {
  createDialogActiveFlag.value = false
  creatingProject.value = {} as Project
}

const handelEditSubmit = () => {
  console.log(editingProject.value)
  editDialogActiveFlag.value = false
}

const handleEditCancel = () => {
  editDialogActiveFlag.value = false
  editingProject.value = {} as Project
}


const deleteItem = (id: number) => {
  deleteDialogActiveFlag.value = true
  deleting.value = id
}

const deleteItemConfirm = async () => {

  deleteDialogActiveFlag.value = false
  let result = (await doDelete(`/projects/${deleting.value}`)) as unknown as Response
  if (result.code === 200) {
    console.log('OK')
    projects.value = (await doGet('/projects')).data
  }
}





const configItem = (item: Project) => {
  configDialogActiveFlag.value = true
  currentConfiguringProject.value = item
}



watch(tab, () => {

  configDatas.value = []

  if (tab.value === 'cmd') {
    configHeaders.value = cmdHeaders
    let cmd = currentConfiguringProject.value.buildCommand
    cmd.forEach((item) => {
      configDatas.value.push({
        name: item.name,
        command: item.command.join(" ")
      })
    })

  } else if (tab.value === 'env') {
    configHeaders.value = envHeaders
    let env = currentConfiguringProject.value.environment
    env.forEach((item) => {
      configDatas.value.push({
        name: item.name,
        value: item.value
      })
    })
  }
})


const configDeleteItem = async (deletedItem: any) => {
  if (tab.value === 'cmd') {
    currentConfiguringProject.value.buildCommand = currentConfiguringProject.value.buildCommand.filter((item) => {
      return item.name !== deletedItem.name
    })
    doPut('/projects', currentConfiguringProject.value)
    projects.value = (await doGet('/projects')).data
  } else if (tab.value === 'env') {
    currentConfiguringProject.value.environment = currentConfiguringProject.value.environment.filter((item) => {
      return item.name !== deletedItem.name
    })
    doPut('/projects', currentConfiguringProject.value)
    projects.value = (await doGet('/projects')).data
  }


}

onMounted(async () => {

  let resp = (await doGet('/projects')) as unknown as Response
  projects.value = resp.data

})

</script>
